<template>
  <div class="manage-container">
    <!-- 场地类型管理 -->
    <div class="form-section">
      <h2>场地类型管理</h2>
      <el-form :inline="true" :model="venueTypeForm" :rules="venueTypeRules" ref="venueTypeFormRef">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="venueTypeForm.name" placeholder="请输入场地类型名称"></el-input>
        </el-form-item>
        <el-form-item label="每小时价格" prop="pricePerHour">
          <el-input-number v-model="venueTypeForm.pricePerHour" :precision="2" :step="0.5" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddVenueType">添加类型</el-button>
        </el-form-item>
      </el-form>

      <!-- 场地类型列表 -->
      <el-table :data="venueTypes" style="width: 100%">
        <el-table-column prop="name" label="类型名称"></el-table-column>
        <el-table-column prop="pricePerHour" label="每小时价格"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEditVenueType(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteVenueType(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 场地管理 -->
    <div class="form-section">
      <h2>场地管理</h2>
      <!-- 筛选和添加场地 -->
      <el-form :inline="true" class="filter-form">
        <el-form-item label="场地类型">
          <el-select v-model="venueFilterForm.venueTypeId" placeholder="请选择场地类型" @change="fetchVenueList">
            <el-option
              v-for="type in venueTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAddVenueConfirm">添加场地</el-button>
        </el-form-item>
      </el-form>

      <!-- 场地列表 -->
      <el-table :data="venues" style="width: 100%">
        <el-table-column prop="number" label="场地编号"></el-table-column>
        <el-table-column prop="name" label="场地名称"></el-table-column>
        <el-table-column prop="pricePerHour" label="每小时价格"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- <el-button size="small" @click="handleEditVenue(scope.row)">编辑</el-button> -->
            <el-button size="small" type="danger" @click="handleDeleteVenue(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑场地类型对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑场地类型"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="venueTypeRules" ref="editFormRef">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入场地类型名称"></el-input>
        </el-form-item>
        <el-form-item label="每小时价格" prop="pricePerHour">
          <el-input-number 
            v-model="editForm.pricePerHour" 
            :precision="2" 
            :step="0.5" 
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiFindVenueType, apiCreateVenueType, apiUpdateVenueType, apiDeleteVenueType } from '@/request/venueType'
import { apiFindVenue, apiCreateVenue, apiUpdateVenue, apiDeleteVenue } from '@/request/venue'
import { useVenueStore } from '@/stores/venue'

// 获取 store 实例
const venueStore = useVenueStore()

// 表单引用
const venueTypeFormRef = ref(null)

// 场地类型表单验证规则
const venueTypeRules = {
  name: [
    { required: true, message: '请输入场地类型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  pricePerHour: [
    { required: true, message: '请输入每小时价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ]
}

// 场地类型表单
const venueTypeForm = reactive({
  name: '',
  pricePerHour: 0
})


// 场地类型列表
const venueTypes = ref([])

// 场地列表
const venues = ref([])

// 场地筛选表单
const venueFilterForm = reactive({
  venueTypeId: ''
})

// 编辑场地类型对话框相关数据
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  name: '',
  pricePerHour: 0
})

onMounted(() => {
  fetchVenueTypeList()
})


// 获取场地类型列表
const fetchVenueTypeList = async () => {
    const res = await apiFindVenueType()
    const types = res.data.venue_types.map(type => ({
        id: type.id,
        name: type.name,
        pricePerHour: type.price_per_hour,
        createdAt: type.created_at,
        updatedAt: type.updated_at
    }))
    
    // 更新 store 中的数据
    venueStore.setVenueTypes(types)
    venueTypes.value = types
    
    if (res.data.len > 0) {
        const firstTypeId = types[0].id
        venueStore.setCurrentVenueTypeId(firstTypeId)
        venueFilterForm.venueTypeId = firstTypeId
        fetchVenueList()
    } else {
        venues.value = []
        ElMessage.warning('请先添加场地类型')
    }
}

// 获取场地列表
const fetchVenueList = async () => {
  try {
    const res = await apiFindVenue(venueFilterForm.venueTypeId)
    if(!res.data || Object.keys(res.data).length === 0 
    || !res.data.venues || res.data.venues.length === 0){
      venues.value = []
      venueStore.setVenues([])
      ElMessage.info('暂无场地')
      return
    }
    const venueList = res.data.venues.map(venue => ({
      id: venue.id,
      number: venue.number,
      name: `${venue.number}号场地`,
      venueTypeId: venue.venue_type_id ,
      pricePerHour: venueTypes.value.find(type => type.id === venue.venue_type_id).pricePerHour,
    }))
    venues.value = venueList
    venueStore.setVenues(venueList)
  } catch (error) {
    venues.value = []
    venueStore.setVenues([])
    ElMessage.error('获取场地列表失败：' + error.message)
  }
}

// 添加场地类型
const handleAddVenueType = async () => {
  if (!venueTypeFormRef.value) return
  
  await venueTypeFormRef.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm('确定要添加该场地类型吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        try {
          await apiCreateVenueType({
            name: venueTypeForm.name,
            price_per_hour: venueTypeForm.pricePerHour
          })
          ElMessage.success('添加成功')
          fetchVenueTypeList()
          venueTypeFormRef.value.resetFields()
        } catch (error) {
          ElMessage.error('添加失败：' + error.message)
        }
      })
    }
  })
}

// 删除场地类型
const handleDeleteVenueType = (row) => {
  ElMessageBox.confirm('确定要删除该场地类型吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除场地类型API
      await apiDeleteVenueType(row.id)
      setTimeout(() => {
        ElMessage.success('删除成功')
      }, 1000)
      // 重新获取场地类型列表
      fetchVenueTypeList()
        // 重置表单
        venueTypeFormRef.value.resetFields()
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  })
}

// 编辑场地类型
const handleEditVenueType = (row) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.pricePerHour = row.pricePerHour
  editDialogVisible.value = true
}

// 确认编辑
const handleEditConfirm = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      ElMessageBox.confirm('确定要保存修改吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await apiUpdateVenueType({
            id: editForm.id,
            name: editForm.name,
            price_per_hour: editForm.pricePerHour
          })
          ElMessage.success('修改成功')
          editDialogVisible.value = false
          fetchVenueTypeList()
        } catch (error) {
          ElMessage.error('修改失败：' + error.message)
        }
      })
    }
  })
}


// 添加场地
const handleAddVenueConfirm = () => {
  if (!venueFilterForm.venueTypeId) {
    ElMessage.warning('请先选择场地类型')
    return
  }
  
  ElMessageBox.confirm('确定要添加该类型的场地吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      
      await apiCreateVenue({ venue_types_id: venueFilterForm.venueTypeId })
      ElMessage.success('添加成功')
      fetchVenueList()
    } catch (error) {
      ElMessage.error('添加失败：' + error.message)
    }
  })
}

// 编辑场地
const handleEditVenue = (row) => {
  // 实现编辑场地的逻辑
}

// 删除场地
const handleDeleteVenue = (row) => {
  ElMessageBox.confirm('确定要删除该场地吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await apiDeleteVenue(row.id)
      ElMessage.success('删除成功')
      // 重新获取场地列表
      fetchVenueList()
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  })
}
</script>

<style scoped>
.manage-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.form-section {
  width: 100%;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
}

.form-section h2 {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

:deep(.el-form) {
  margin-bottom: 20px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-input), :deep(.el-input-number) {
  width: 200px;
}

:deep(.el-select) {
  width: 200px;
}

.filter-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
